<template>
  <span>
    <el-upload :accept="accept" class="new-upload" action="/" :before-upload="uploadImg">
      <el-button v-if="!uploadData.isPdf" size="medium" width="144px" type="default">{{ coverImg ? '更换图片' : '点击上传图片' }}</el-button>
      <el-button v-else size="medium" width="144px" type="default">{{ coverImg ? '更换PDF' : '点击上传PDF' }}</el-button>
    </el-upload>
    <a v-if="coverImg && uploadData.isPdf" :href="coverImg" target="_blank">{{ uploadData.pdfName || coverImg }}</a>
    <el-image v-if="coverImg && !uploadData.hideImg" style="width: 100px; height: 100px" :src="coverImg" :preview-src-list="[coverImg]"> </el-image>
  </span>
</template>
<script>
export default {
  name: 'newUpload',
  props: {
    uploadData: {
      type: Object
    },
    accept: {
      type: String,
      default: 'image/*'
    }
  },
  computed: {
    coverImg() {
      return this.uploadData.coverImg || ''
    }
  },
  methods: {
    uploadImg(file) {
      const typeArry = this.uploadData.isPdf ? ['.pdf'] : ['.jpg', '.png', '.bmp', '.JPG', '.PNG', '.BMP', '.gif', '.GIF']
      const type = file.name.substring(file.name.lastIndexOf('.'))
      const isImage = typeArry.indexOf(type) > -1
      if (!isImage) {
        this.$message.warning('上传文件类型不正确，请检查后重新上传！')
        return false
      }
      let formData = new FormData()
      formData.append('file', file)
      if (this.uploadData.formdata) {
        this.uploadData.formdata.forEach(key => {
          formData.append(key, this.uploadData[key])
        })
      }
      this.$httpFun({
        url: this.uploadData.url,
        data: formData,
        methods: 'post',
        responseType: {
          isform: true
        }
      }).then(res => {
        if (res.code === 0) {
          this.$emit('uploadSuccess', {
            key: this.uploadData.key,
            ...res.data
          })
        } else {
          alert(res.message)
        }
      })
      return false
    }
  }
}
</script>
<style lang="scss">
.new-upload {
  max-height: 100px;
  position: relative;
  overflow: hidden;
  
  .el-upload {
    .el-button--medium,
    img {
      display: block;
    }
  }
}
</style>
